package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.customview.LoadMoreListView;
import com.shwread.android.ui.customview.LoadMoreListView.OnLoadMoreListener;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.android.ui.widget.BookCoverView;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.JSONUtil;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.tgx.tina.android.task.ATaskService;
import org.apache.http.Header;
import org.json.JSONException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import logic.bean.BookInfo;
import logic.bean.ResultColumninfosNew;
import logic.util.NetworkUtil;
import logic.util.Util;

public class BookSearchActivity extends BaseBusinessActivity implements OnClickListener, OnItemClickListener {

	@SuppressLint("HandlerLeak")
	private Handler					handler			= new Handler() {

														@Override
														public void handleMessage(Message msg) {
															switch (msg.what) {
																case 100:
																	lvBooks.onLoadMoreComplete();
																	if (booksList.size() > 0) {

																		rlayBookSearchBlackBg.setVisibility(View.GONE);
																		rlayBookSearchResult
																				.setVisibility(View.VISIBLE);
																		lvBooks.setVisibility(View.VISIBLE);
																		tvNoBooks.setVisibility(View.GONE);
																		bookAdapter.notifyDataSetChanged();
																		TextIsChange = false;
																		btnSearch.setText("取消");
																	}
																	else {
																		rlayBookSearchBlackBg.setVisibility(View.GONE);
																		rlayBookSearchResult
																				.setVisibility(View.VISIBLE);
																		tvNoBooks.setVisibility(View.VISIBLE);
																		lvBooks.setVisibility(View.GONE);
																	}

																	break;
																case 101:
																	rlayBookSearchBlackBg.setVisibility(View.GONE);
																	rlayBookSearchResult.setVisibility(View.VISIBLE);
																	tvNoBooks.setVisibility(View.VISIBLE);
																	lvBooks.setVisibility(View.GONE);
																	Util.showToast(mContext, (String) msg.obj);
																	break;
																default:
																	break;
															}
														}

													};

	private ResultColumninfosNew		resultInfo;
	private List<BookInfo>			booksList;
	private BookAdapter				bookAdapter;
	private Context					mContext;
	private TextView				tvNoBooks;
	// private ListView lvBooks;
	private LoadMoreListView		lvBooks;
	private RelativeLayout			rlayBookSearchBlackBg, rlayBookSearchResult;
	// private static boolean FindBooks = false;
	private static boolean			TextIsChange	= false;
	private Button					btnSearch, btnClear;
	private ImageView				ivIcon;
	private AutoCompleteTextView	autotvBookName;
	public int						currentPage		= 1;
	public int						totalPage		= 1;
	public String					condition;

	// 隐藏系统输入法
	InputMethodManager				mInputMethodManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.book_search);
		mContext = this;
		mAService = new ATaskService();
		mAService.startAService(this);

		initData();
		initView();
		setLinstener();
	}
	private void setLinstener() {
		ivIcon.setOnClickListener(this);
		btnClear.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
		autotvBookName.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				if (TextUtils.isEmpty(arg0)) {
					TextIsChange = false;
					btnClear.setVisibility(View.GONE);
					btnSearch.setText("取消");
				}
				else {
					TextIsChange = true;
					btnClear.setVisibility(View.VISIBLE);
					btnSearch.setText("搜索");
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable arg0) {
			}
		});
		lvBooks.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				final BookInfo bean = (BookInfo) arg0.getAdapter().getItem(arg2);
				//#ifdef SHOW_OLDBOOKDETAIL
				//$ Intent intent = new Intent(BookSearchActivity.this, BookDetailActivity.class);
				//#else
				Intent intent = new Intent(BookSearchActivity.this, NewBookDetailActivity.class);
				//#endif
				intent.putExtra("BookInfo", bean);
				startActivity(intent);
			}
		});
	}

	private void initView() {
		ivIcon = (ImageView) findViewById(R.id.book_read_search_searchbox_icon_iv);
		btnClear = (Button) findViewById(R.id.book_read_search_searchbox_clear_btn);
		btnSearch = (Button) findViewById(R.id.book_read_search_search_btn);
		autotvBookName = (AutoCompleteTextView) findViewById(R.id.book_read_search_searchbox_edit_autotv);

		tvNoBooks = (TextView) findViewById(R.id.book_search_result_no_books_tv);
		lvBooks = (LoadMoreListView) findViewById(R.id.book_search_result_books_lv);
		rlayBookSearchBlackBg = (RelativeLayout) findViewById(R.id.book_search_black_rlay);
		rlayBookSearchResult = (RelativeLayout) findViewById(R.id.book_search_result_rlay);
		rlayBookSearchBlackBg.setVisibility(View.VISIBLE);
		mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		Util.showInputMethodManager(this);
		lvBooks.setAdapter(bookAdapter);

		lvBooks.setOnItemClickListener(this);
		lvBooks.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				if (totalPage >= currentPage) {
					currentPage++;
//					new QryBooksByNameOrAuthurAction(mContext, condition, currentPage, 10, new BookListener2()).start();
					ActionHelp.qryBooksByNameOrAuthur(mContext, condition, currentPage, 10, new BookHandler2());
				}
				else {
					lvBooks.onLoadMoreComplete();
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.book_read_search_searchbox_edit_autotv:
				break;
			case R.id.book_read_search_searchbox_clear_btn:
				autotvBookName.setText("");
				rlayBookSearchBlackBg.setVisibility(View.VISIBLE);
				rlayBookSearchResult.setVisibility(View.GONE);
				break;
			case R.id.book_read_search_search_btn:
				if (TextIsChange) {
					Util.hideInputMethodManager(this, autotvBookName);
					searchBook();// 调用搜索方法,并且返回搜索状态标志 FindBooks
					// if (FindBooks)
					// {
					// FindBooks = false; //测试用
					// lvBooks.setAdapter(new BookAdapter());
					// rlayBookSearchBlackBg.setVisibility(View.GONE);
					// rlayBookSearchResult.setVisibility(View.VISIBLE);
					// lvBooks.setVisibility(View.VISIBLE);
					// tvNoBooks.setVisibility(View.GONE);
					// break;
					// }
					// else
					// {
					// FindBooks = true; //测试用
					// rlayBookSearchBlackBg.setVisibility(View.GONE);
					// rlayBookSearchResult.setVisibility(View.VISIBLE);
					// tvNoBooks.setVisibility(View.VISIBLE);
					// lvBooks.setVisibility(View.GONE);
					// break;
					// }
				}
				else {// 取消搜索
					onBackPressed();
					// 隐藏系统输入法
					Util.hideInputMethodManager(this, autotvBookName);

					// llayBookSearch.setVisibility(View.GONE);
					rlayBookSearchBlackBg.setVisibility(View.VISIBLE);
					rlayBookSearchResult.setVisibility(View.GONE);
					tvNoBooks.setVisibility(View.GONE);
					lvBooks.setVisibility(View.GONE);
					break;
				}

			default:
				break;
		}

	}

	// 搜索方法 所搜到 返回标志成功，没有搜索到，返回标志失败；
	private void searchBook() {
		condition = autotvBookName.getText().toString().trim();
		currentPage = 1;
		if (Util.isEmpty(condition)) {
			Util.showToast(mContext, "搜索内容不能为空哦");
		}
		else if (NetworkUtil.isNetAvailable(mContext)) {
//			new QryBooksByNameOrAuthurAction(mContext, condition, currentPage, 10, new BookListener1()).start();
			ActionHelp.qryBooksByNameOrAuthur(mContext, condition, currentPage, 10, new BoolHandler1());
		}
		else {
			new NetworkDialog(mContext).show();
		}

	}

	private class BoolHandler1 extends ObjectHttpResponseHandler<ResultColumninfosNew>
	{

		@Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
	        if (statusCode>1000)
            {
				  try
		    	   {
		    		   Message msg = Message.obtain();
		    		   msg.what = 101;
		               msg.obj = JSONUtil.getString(responseString);
		               handler.sendMessage(msg);
		    	   }
		    	   catch (JSONException e)
		    	   {
		    		   e.printStackTrace();
		    	   }
				
            }
        }

		@Override
        public void onSuccess(int statusCode, Header[] headers, ResultColumninfosNew object, String responseString) {
			resultInfo = object;
			totalPage = resultInfo.getTotalPage();
			if (booksList.size() > 0) booksList.removeAll(booksList);
			// lvBooks.setSelectionFromTop( );
			booksList.addAll(resultInfo.getBooks());
			handler.sendEmptyMessage(100);
        }

		@Override
        public Type getType() {
	        return  new TypeToken<ResultColumninfosNew>(){}.getType();
        }
		
	}
	
	
	/**
	 * 收索结果首页显示
	 * 
	 * @author Administrator
	 *
	 */
	class BookListener1 implements ActionListener {

		@Override
		public void OK(Object obj) {
			resultInfo = (ResultColumninfosNew) obj;
			totalPage = resultInfo.getTotalPage();
			if (booksList.size() > 0) booksList.removeAll(booksList);
			// lvBooks.setSelectionFromTop( );
			booksList.addAll(resultInfo.getBooks());
			handler.sendEmptyMessage(100);
		}

		@Override
		public void ERROR(int resultCode, final String message) {
			Message msg = Message.obtain();
			msg.what = 101;
			msg.obj = message;
			handler.sendMessage(msg);
		}

		@Override
		public void HTTPERROR(int statusCode) {

		}

	}

	private class BookHandler2 extends ObjectHttpResponseHandler<ResultColumninfosNew>
	{

		@Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
	       if (statusCode > 1000)
	       {
	    	   try
	    	   {
	    		   Message msg = Message.obtain();
	    		   msg.what = 101;
	               msg.obj = JSONUtil.getString(responseString);
	               handler.sendMessage(msg);
	    	   }
	    	   catch (JSONException e)
	    	   {
	    		   e.printStackTrace();
	    	   }
        	}
        }

		@Override
        public void onSuccess(int statusCode, Header[] headers, ResultColumninfosNew object, String responseString) {
			resultInfo = object;
			booksList.addAll(resultInfo.getBooks());
			handler.sendEmptyMessage(100);
        }

		@Override
        public Type getType() {
	        return new TypeToken<ResultColumninfosNew>(){}.getType();
        }
		
	}
	
	
	
	/**
	 * 下拉刷新显示
	 * 
	 * @author Administrator
	 *
	 */

	class BookListener2 implements ActionListener {

		@Override
		public void OK(Object obj) {
			resultInfo = (ResultColumninfosNew) obj;
			booksList.addAll(resultInfo.getBooks());
			handler.sendEmptyMessage(100);
		}

		@Override
		public void ERROR(int resultCode, final String message) {
			Message msg = Message.obtain();
			msg.what = 101;
			msg.obj = message;
			handler.sendMessage(msg);
		}

		@Override
		public void HTTPERROR(int statusCode) {

		}

	}

	private class BookAdapter extends BaseAdapter {

		ViewHolder holder;

		@Override
		public int getCount() {
			return booksList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return booksList.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				holder = new ViewHolder();
				convertView = getLayoutInflater().inflate(R.layout.common_book_item, null);
				holder.ivCover = (BookCoverView) convertView.findViewById(R.id.common_book_item_cover);
//				holder.ivCover = (SmartImageView) convertView.findViewById(R.id.common_book_item_cover);
				holder.tvBookName = (TextView) convertView.findViewById(R.id.common_book_item_name);
				holder.tvAuthor = (TextView) convertView.findViewById(R.id.common_book_item_author);
				holder.tvIntro = (TextView) convertView.findViewById(R.id.common_book_item_intro);
				holder.ivMusic_flag = (ImageView) convertView.findViewById(R.id.common_book_item_type_img);
				convertView.setTag(holder);
			}
			else {
				holder = (ViewHolder) convertView.getTag();
			}
			final BookInfo info = booksList.get(position);
			holder.ivCover.setImageUrl(info.getLogoUrl(),info.getCoverTagPicUrl());
//			holder.ivCover.setImageUrl(info.getLogoUrl());
			holder.tvBookName.setText(info.getName());
			holder.tvAuthor.setText("作者：" + info.getAuthor());
			holder.tvIntro.setText(info.getShortIntro());
			setBookTypeIcon(holder.ivMusic_flag, info.getContent_type());

			return convertView;
		}

	}

	class ViewHolder {
		BookCoverView	ivCover;
//		SmartImageView	ivCover;
		TextView		tvBookName;
		TextView		tvAuthor;
		TextView		tvIntro;
		ImageView		ivMusic_flag;
	}

	private void initData() {
		booksList = new ArrayList<BookInfo>();
		bookAdapter = new BookAdapter();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if (mAService != null) mAService.stopAService();
		super.onDestroy();
	}

	@Override
	public Handler getUIHandler() {
		return handler;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		final BookInfo bean = (BookInfo) parent.getAdapter().getItem(position);
		//#ifdef SHOW_OLDBOOKDETAIL
		//$ Intent intent = new Intent(BookSearchActivity.this, BookDetailActivity.class);
		//#else
		Intent intent = new Intent(BookSearchActivity.this, NewBookDetailActivity.class);
		//#endif
		intent.putExtra("BookInfo", bean);
		startActivity(intent);
	}

}
